#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/select.h>

#define PORT 8888
#define MAX_CLIENTS  FD_SETSIZE  // select 能监听的最大描述符数

int main()
{
    int server_fd, new_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_len = sizeof(client_addr);
    int client_fds[MAX_CLIENTS];  // 保存所有客户端的 fd
    fd_set all_fds, read_fds;     // 描述符集合
    int max_fd;

    // 创建 socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) { perror("socket"); exit(1); }

    // 绑定端口
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);
    if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind"); exit(1);
    }

    // 监听
    if (listen(server_fd, 10) < 0) {
        perror("listen"); exit(1);
    }

    // 初始化客户端 fd 列表
    for (int i = 0; i < MAX_CLIENTS; ++i) client_fds[i] = -1;

    // 设置监听集合
    FD_ZERO(&all_fds);
    FD_SET(server_fd, &all_fds);
    max_fd = server_fd;

    printf("Chatroom Server listening on port %d...\n", PORT);
    while (1)
    {
        read_fds = all_fds;  // 每次都重新赋值
        int n_ready = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
        if (n_ready < 0)
        {
            perror("select"); exit(1);
        }

        // 有新连接
        if (FD_ISSET(server_fd, &read_fds))
        {
            new_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
            if (new_fd < 0)
            {
                perror("accept"); continue;
            }

            // 加入 client_fds 列表
            int i;
            for (i = 0; i < MAX_CLIENTS; ++i)
            {
                if (client_fds[i] == -1)
                {
                    client_fds[i] = new_fd;
                    break;
                }
            }
            if (i == MAX_CLIENTS)
            {
                fprintf(stderr, "Too many clients\n");
                close(new_fd);
                continue;
            }

            FD_SET(new_fd, &all_fds);             // 加入监听集合
            if (new_fd > max_fd) max_fd = new_fd; // 更新 max_fd

            char ip[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &client_addr.sin_addr, ip, sizeof(ip));
            printf("New connection from %s:%d\n", ip, ntohs(client_addr.sin_port));

            if (--n_ready <= 0) continue; // 已处理完事件
        }

        // 接收来自客户端的消息
        for (int i = 0; i < MAX_CLIENTS; ++i)
        {
            int fd = client_fds[i];
            if (fd < 0) continue;

            if (FD_ISSET(fd, &read_fds))
            {
                char buffer[1024];
                int n = recv(fd, buffer, sizeof(buffer) - 1, 0);
                if (n <= 0)
                {
                    // 客户端断开
                    printf("Client %d disconnected\n", fd);
                    close(fd);
                    FD_CLR(fd, &all_fds);
                    client_fds[i] = -1;
                }
                else
                {
                    buffer[n] = '\0';
                    printf("Client %d says: %s\n", fd, buffer);
                    // 广播消息给所有其他客户端
                    for (int j = 0; j < MAX_CLIENTS; ++j)
                    {
                        int other_fd = client_fds[j];
                        if (other_fd != -1 && other_fd != fd)
                        {
                            send(other_fd, buffer, n, 0);
                        }
                    }
                }
                if (--n_ready <= 0) break; // 已处理完
            }
        }
    }
}
